from core.skill.career.career_list import CareerList 
from core.skill.career.skill_type import SkillType
import time
from utils import logger
from collections import deque
from utils.ocr import ColorNumberRecognizer , GlobalOcr

# 技能循环
class SkillCycle:
    def __init__(self, career_name: str):
        self.hwnd = 395592
        # 职业名称
        self.career_name = career_name
        # 职业信息
        self.career_info = CareerList().get_career(career_name)
        # 是否运行
        self.is_running = False
        # 目标是否存在
        self.target_exists = False
        # 血量
        self.health = 100
        # 内力  
        self.mp = 6100
        # 怒气  
        self.rage = 0
        # 冷却时间记录
        self.cooldown_timers = {}  
        # BUFF持续时间记录
        self.buff_timers = {}  
        # 技能优先级队列
        self.skill_queue = deque()
        self.color_number_recognizer = ColorNumberRecognizer(GlobalOcr())

    # 开始循环  
    def start(self):
        self.is_running = True
        self.loop()

    # 结束循环
    def stop(self):
        self.is_running = False

    # 循环
    def loop(self):
        while self.is_running:
            # 读取当前内力、血量和怒气值
            self.read_current_status()
            
            if self.target_exists:
                self.execute_skills()
            else:
                print("无目标，等待5秒后束循环")
                time.sleep(5)
                self.stop()

    # 读取当前内力、血量和怒气值
    def read_current_status(self):
        if self.rage < 100:
            self.pick_energy()
            self.rage = self.rage + 10
        # print(f"当前血量: {self.health}")
        # print(f"当前能量: {self.mp}")
        # print(f"当前怒气: {self.rage}")
        # print(f"当前冷却时间: {self.cooldown_timers}")
        # print(f"当前BUFF持续时间: {self.buff_timers}")
        print("------------------------")

    # 执行技能
    def execute_skills(self):
        time.sleep(1)
        
        # 优先使用队列中的技能
        if self.skill_queue:
            skill = self.skill_queue.popleft()
            if self.can_use_skill(skill):
                self.use_skill(skill)
                return
        
        # 如果队列为空或队列中的技能不可用，则按优先级选择技能
        skills = self.career_info["skills"]
        available_skills = [skill for skill in skills.values() if self.can_use_skill(skill)]
        if available_skills:
            available_skills.sort(key=lambda x: x["priority"])
            self.use_skill(available_skills[0])
        else:
            print("没有可用的技能")

    # 检查技能是否可用
    def can_use_skill(self, skill):
        # 检查能量和怒气是否足够
        if self.mp < skill["mp"] or self.rage < skill["rage"]:
            # print(f"能量或怒气不足，无法使用技能: {skill['name']} ; 当前能量: {self.mp} ; 当前怒气: {self.rage}")
            return False
        
        # 检查技能冷却时间
        current_time = time.time() * 1000  # 转换为毫秒
        if skill["name"] in self.cooldown_timers:
            # print(f"技能冷却中，无法使用技能: {skill['name']} ; 当前冷却时间: {self.cooldown_timers[skill['name']] - current_time}")
            if current_time < self.cooldown_timers[skill["name"]]:
                # 冷却时间未结束
                # print(f"技能冷却时间未结束，无法使用技能: {skill['name']}")
                return False
        
        # 检查技能冲突
        for conflict_skill in skill.get("conflict", []):
            if conflict_skill in self.buff_timers:
                if current_time < self.buff_timers[conflict_skill]:
                    print(f"技能冲突，无法使用技能: {skill['name']} ; 当前BUFF持续时间: {self.buff_timers[conflict_skill] - current_time}")
                    return False
        
        
        return True

    # 使用技能
    def use_skill(self, skill):
        release_count = skill.get("release_count", 1)
        for _ in range(release_count):
            print(f"使用技能: {skill['name']} type: {skill['type']}; 剩余释放次数: {release_count - _} ; 技能图片: {skill['image']}")
            time.sleep(1.3)
            self.mp -= skill["mp"]
            self.rage -= skill["rage"]  
            
            # 设置技能冷却时间
            current_time = time.time() * 1000  # 转换为毫秒
            if skill["cd"] > 0:
                self.cooldown_timers[skill["name"]] = current_time + skill["cd"]
            
            # 设置BUFF持续时间
            if skill["duration"] > 0:
                self.buff_timers[skill["name"]] = current_time + skill["duration"] * 1000
                
            # 处理连招技能
            self.add_combo_skills(skill)

    # 添加连招技能
    def add_combo_skills(self, skill):
        """将连招技能加入队列前方"""
        if "combo" in skill and skill["combo"]:
            # 将连招技能按顺序添加到队列前方
            for combo_skill_name in reversed(skill["combo"]):
                # 从技能列表中获取连招技能
                combo_skill = self.career_info["skills"].get(combo_skill_name)
                if combo_skill:
                    self.add_skill_to_front(combo_skill)
                    # print(f"连招技能 {combo_skill['name']} 已加入队列前方")

    # 获取技能循环
    def get_skill_cycle(self):
        return self.career_info.get("skill_cycle", None)

    # 设置技能循环
    def set_skill_cycle(self, skill_cycle: int):
        self.career_info["skill_cycle"] = skill_cycle

    # 模拟目标检测
    def detect_target(self, exists: bool):
        self.target_exists = exists

    # 将技能加入队列前方
    def add_skill_to_front(self, skill):
        self.skill_queue.appendleft(skill)
        # print(f"技能 {skill['name']} 已加入队列前方")

    def pick_energy(self):
        try:
            # 获取当前能量值
            current_energy = self.color_number_recognizer.recognize_number(
                self.hwnd, 
                    # hwnd=hwnd,
                start_point=(161, 103),  # 这里需要根据实际UI位置调整
                size=(24, 14),
                debug=True,
            confidence_threshold=0.01,
            )
            print(current_energy)
            # 解析能量值
            if '/' in current_energy:
                current, max_energy = map(int, current_energy.split('/'))
                if current < max_energy:
                    # 执行拾取能量的按键操作
                    # keyboard.press('f')  # 假设F键是拾取能量的按键
                    # time.sleep(0.1)
                    # keyboard.release('f')
                    logger.info(f"拾取能量成功，当前能量: {current}/{max_energy}")
                    return True
                    
            return False
            
        except Exception as e:
            logger.error(f"拾取能量失败: {e}")
            return False

# 示例用法
# def main():
#     skill_cycle = SkillCycle("蜀山")
#     skill_cycle.detect_target(True)  # 模拟目标存在
#     skill_cycle.start()

# if __name__ == "__main__":
#     main()

